import { NzMessageService } from 'ng-zorro-antd/message';
import { AbsFormUtil } from '@abstract/form';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { HttpCacheService } from '@core/net/http-cache.service';
import { TOKEN, USER_LOGIN } from '@app/store/dict';
import { LoginService } from '@service/login.service';
import { Router, ActivatedRoute } from '@angular/router';
import { SystemService } from '@service/system.service';
import { TreeService } from '@service/tree.service';
import { ResTypeEnum } from '@app/store/dict';
import { AuthService } from '@service/auth.service';
import { Auth } from '@app/store/auth.enum';

@Component({
	selector: 'app-login',
	templateUrl: './login.component.html',
	styleUrls: ['./login.component.less']
})
export class LoginComponent extends AbsFormUtil implements OnInit {
	validateForm: FormGroup;
	nzLoading = false;
	redirectUrl = '';

	menuList = [];
	constructor(
		private fb: FormBuilder,
		private httpCacheService: HttpCacheService,
		private loginService: LoginService,
		private nzMessageService: NzMessageService,
		private router: Router,
		private route: ActivatedRoute,
		private systemService: SystemService,
		private treeService: TreeService,
		private authService: AuthService
	) {
		super();
		this.redirectUrl = this.route.snapshot.queryParamMap.get('redirectUrl');
	}

	ngOnInit() {
		this.buildForm();
		const loginStr = this.httpCacheService.getLocalCache(USER_LOGIN);
		if (loginStr) {
			const loginInfo = JSON.parse(loginStr);
			this.validateForm.patchValue(loginInfo);
		}
	}

	async onSubmit() {
		this.markAsDirty();
		if (!this.validateForm.valid) {
			return;
		}
		if (this.validateForm.value.remember) {
			this.httpCacheService.saveLocalCache(USER_LOGIN, JSON.stringify(this.validateForm.value));
		}
		this.nzLoading = true;
		const messageId = this.nzMessageService.loading('登录中, 请稍后', {nzDuration: 0});
		const validateForm = this.validateForm.value;
		const result = await this.loginService.login(validateForm);
		if (result.code === 500) {
			this.nzMessageService.error(result.msg);
			this.nzLoading = false;
			this.nzMessageService.remove(messageId.messageId);
			return;
		}
		this.httpCacheService.saveSessionCache(TOKEN, result.token);
		const userInfo = await this.loginService.getUserInfoData();
		if (userInfo.code !== 0) {
			this.nzMessageService.success('获取登录用户信息失败,请稍后再试');
			return;
		}
		this.loginService.saveUserInfo(userInfo);

		// 获取菜单
		const showMenuRes = await this.loginService.getShowMenu();
		// 保存菜单
		this.loginService.saveMenu(showMenuRes.resources);
		// 获取权限
		const permissionsRes = await this.loginService.getPermissions();
		// 保存菜单
		this.authService.saveAuth(permissionsRes.permissions);


		// 获取菜单以及权限
		// const resultMenu = await this.systemService.getResourceList();
		// this.menuList = resultMenu.list;
		// this.getRoleList(userInfo.role);
		const byUrl = this.redirectUrl ? this.redirectUrl : '/page/home';
		this.router.navigateByUrl(byUrl);
		this.nzMessageService.remove(messageId.messageId);
		this.nzLoading = false;
	}


	buildForm() {
		this.validateForm = this.fb.group({
			loginName: [null, [Validators.required]],
			password: [null, [Validators.required]],
			remember: [false]
		});
	}

	async getRoleList(idx: string[]) {
		// return new Promise(async (res, rej) =>{
			const result = await this.systemService.getRoleInfoList(idx);
			const resTreeList = result.map(it => it.resources);
			const roleIds = [];
			let treeToList = [];
			const auth = [];
			resTreeList.forEach(resTree => {
				this.listToChildren(resTree);
				treeToList = this.treeService.convertTreeToList(resTree);
				const checkedRoleIds = treeToList.filter(itm => itm.checked).map(it => it.id);
				roleIds.push(...checkedRoleIds);
			});
			const resRoleIds = Array.from(new Set(roleIds));
			treeToList.forEach(it =>{
				// const menu = this.menuList.find(itm => it.id === itm.id);
				// if (menu){
				// 	it.resUrl = menu.resUrl;
				// 	it.permission = menu.permission;
				// }
				if (resRoleIds.includes(it.id)) {
					it.check = true;
				}
			});
			// treeToList.forEach(it => {
			// 	it.check = it.check ? it.check : this.isChildrenCheck(it.id, treeToList);
			// });
			treeToList.forEach(it => {
				const menu = this.menuList.find(itm => it.id === itm.id);
				if (menu && it.check){
					if (menu.resType === ResTypeEnum.Botton) {
						// 获取权限code
						auth.push(menu.permission);
					}
				}
				
			});
			// let tree = this.treeService.convertListToTree(treeToList, 0);
			// tree = tree.filter(it => it.check);
			
			//  保存按钮权限
			this.authService.saveAuth(auth);
			// res(true);

		// })
		

		
	}

	isChildrenCheck(id: number, treeToList: any[]){
		const childList = treeToList.filter(it => it.parentId === id);
		if (childList?.length) {
			if (childList.some(itm => itm.check)) {
				return true;
			}
			childList.forEach(item => {
				this.isChildrenCheck(item.id, treeToList);
			});
		}
	}

	listToChildren(list: any[]) {
		if (list) {
			list.forEach(itm => {
				itm.children = itm.list || [];
				itm.id = itm.value * 1;
				if (itm.list?.length) {
					this.listToChildren(itm.list);
				}
			});
		}
	}
	
}
